package com.utils.failureanalysis.data.util;

import com.utils.failureanalysis.exceptions.fileNotFoundException.EmptyFolderException;
import com.utils.failureanalysis.exceptions.fileNotFoundException.VideoNotFoundException;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

public class VideoTools {
    //    public static final String videoFolder="D:\\jenkins\\video";
//    0707013227.mp4
    public static final String videoFolder = "D:\\jenkins\\video";

    public String relatedVideo(String date) throws EmptyFolderException, VideoNotFoundException {
        String videoName = filter(dirFile(),date);
        return videoName;
    }

    public String[] dirFile() throws EmptyFolderException {
        File videoFolderFile = new File(videoFolder);
        String[] filesList = videoFolderFile.list();
//        目标文件夹为空！视频根目录不正确，或视频已删除
        if(filesList.length==0){
            throw new EmptyFolderException();
        }
        return filesList;
    }

    /**
     * 设置筛选规则，筛选出相关video的文件名
     * 需要先统一数据格式，通过ArrayList，进行排序
     *
     * @param filesList
     * @param date
     * @return
     */
    public String filter(String[] filesList, String date) throws VideoNotFoundException {
//        TODO:ATTENTION hostlog.zip 中无年数据，手动获取当前时间，添加年数据，这可能会引起数据查找不准确，另外精确到分钟，精确度引起误差
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date currentYear = new Date();
        String formatYear = sdf.format(currentYear);
        String mDate=formatYear+date.replaceAll("[^\\d]","").substring(0,8);
        String formatDate=mDate+".mp4";

//        格式化成video name形式进行排序
        List<String> videwList=Arrays.asList(filesList);
        ArrayList<String> videoArrayList=new ArrayList<>(videwList);
        videoArrayList.add(formatDate);
        Collections.sort(videoArrayList);
        for(String s:videoArrayList){
            System.out.println(s);
        }

//        取出前一个值 非空判断 数组越界判断
        int index=videoArrayList.indexOf(formatDate);
        if(index<1){
            throw new VideoNotFoundException();
        }
        String videoName=videoArrayList.get(index-1);
        return videoName;
    }

    /*public static void main(String[] args) {
        VideoTools vt=new VideoTools();
        String testDate="07-08 14:26:48";
        String[] namesList = new String[5];
        namesList[0] = "201807081422.mp4";
        namesList[1] = "201807081425.mp4";
        namesList[2] = "201807081432.mp4";
        namesList[3] = "201807081430.mp4";
        namesList[4] = "201807081435.mp4";
        vt.relatedVideo(testDate);
        System.out.println(vt.filter(namesList,testDate));
    }*/
}
